package com.shipwe.loans.ui.activity

import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.shipwe.loans.R
import com.shipwe.loans.databinding.ActivityPermissionsBinding
import com.shipwe.loans.databinding.PermissionIndicatorBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.pro.ShipweFragment
import com.shipwe.loans.ui.fragment.FragmentPermission
import com.shipwe.loans.ui.presenter.UserPermissionPresenter
import com.shipwe.loans.ui.view.IUserPermissionView
import com.shipwe.loans.utils.ShipweTitleBarUtil
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.ShipweAppAnalysisHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:04
 * @Annotation：权限
 */
class ActivityPermission: ShipweActivity(),IUserPermissionView {
    lateinit var binding: ActivityPermissionsBinding
    var isFirstIn = true

    var presenter: UserPermissionPresenter? = null
    private var pageList: ArrayList<ShipweFragment>? = null

    override fun getShipweRootView(): View? {
        binding = ActivityPermissionsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        ShipweTitleBarUtil.setStatusBarLightMode(this, false)
        pageList = arrayListOf()
    }

    override fun initShipweListener() {
        binding.permissionViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (!isFirstIn){
                    presenter!!.onUserPermissionCheckPageClick(position)
                }
            }
        })

        binding.permissionLast.setOnClickListener {
            if (presenter!!.curtIndex == 0){
                return@setOnClickListener
            }
            val showIndex = presenter!!.curtIndex - 1
            binding.permissionViewPager.currentItem = showIndex
        }

        binding.permissionNext.setOnClickListener {
            if (presenter!!.curtIndex == presenter!!.getUserPermissionList().size - 1){
                return@setOnClickListener
            }
            val showIndex = presenter!!.curtIndex + 1
            binding.permissionViewPager.currentItem = showIndex
        }

        binding.permissionCheckBox.setOnCheckedChangeListener { _, isChecked ->
            when (isChecked) {
                true -> {
                    binding.permissionAgree.isEnabled = true
                }
                false -> {
                    binding.permissionAgree.isEnabled = false
                }
            }
        }
        //拒绝
        binding.permissionDeny.setOnClickListener {
            presenter!!.onUserPermissionDenyClick()
        }

        //同意权限
        binding.permissionAgree.setOnClickListener {
            presenter!!.onUserPermissionAgreeClick()
        }

        //已授权
        binding.permissionAuthorized.setOnClickListener{
        }

        //被禁止
        binding.permissionBanned.setOnClickListener {
            presenter!!.onUserPermissionBannedClick()
        }
    }

    override fun initShipweData() {
        presenter = UserPermissionPresenter(this)
        presenter!!.loadUserPermissionListAction()
    }

    override fun onResume() {
        super.onResume()
        if (!isFirstIn){
            presenter?.onUserPermissionResume()
        }
    }

    /**
     * 设置权限列表
     */
    override fun showPermissionList(pList: ArrayList<JSONObject>) {
        pList.forEach {
            pageList?.add(FragmentPermission(it))
        }
        val pageAdapter = MyFragmentPagerAdapter(this,pageList!!)
        binding.permissionViewPager.adapter = pageAdapter
    }

    /**
     * 设置显示权限
     */
    override fun showPermissionPage(index: Int) {
        isFirstIn = false
        binding.permissionViewPager.currentItem = index
        addIndicatorViews(index)

        val item = presenter!!.getUserPermissionList()[index]
        binding.permissionIcon.setImageResource(item.optInt("icon"))
        binding.permissionTitle.text = item.optString("title")
        binding.permissionTitle.setTextColor(item.optInt("titleColor"))
    }

    /**
     * 未申请
     */
    override fun showPermissionNotObtained() {
        binding.permissionDefault.visibility = View.VISIBLE
        binding.permissionAuthorized.visibility = View.GONE
        binding.permissionBanned.visibility = View.GONE

        binding.permissionTipsLayout.visibility = View.VISIBLE

        binding.permissionCheckBox.isChecked = true
        binding.permissionAgree.isEnabled = true
    }

    /**
     * 已允许
     */
    override fun showPermissionAuthorized() {
        binding.permissionDefault.visibility = View.GONE
        binding.permissionAuthorized.visibility = View.VISIBLE
        binding.permissionBanned.visibility = View.GONE

        binding.permissionTipsLayout.visibility = View.GONE
    }

    /**
     * 已拒绝
     */
    override fun showPermissionBanned() {
        binding.permissionDefault.visibility = View.GONE
        binding.permissionAuthorized.visibility = View.GONE
        binding.permissionBanned.visibility = View.VISIBLE

        binding.permissionTipsLayout.visibility = View.GONE
    }

    /**
     * 进入登录页面
     */
    override fun showPermissionSuccess() {
        //已登录
        if (ShipweSharedHelper.getShipweSharedBoolean(ShipweSharedKey.SHIPWE_LOGIN)){
            //初始化analysis lib 赋值 用户id 和 token
            ShipweAppAnalysisHelper.initAnalysisLibAtLoginSuccess()
            onIntent(ActivityMain::class.java)
        } else {
            onIntent(ActivityLogin::class.java)
        }
        finish()
    }

    /**
     * 添加指示器
     */
    private fun addIndicatorViews(index: Int){
        val item = presenter!!.getUserPermissionList()[index]
        binding.permissionIndicator.removeAllViews()
        for (i in 0..<pageList!!.size){
            val indicatorBinding = PermissionIndicatorBinding.inflate(layoutInflater)
            when (i){
                index -> {
                    indicatorBinding.imgView.setImageResource(R.drawable.permission_indicator_select)
                }
                else -> {
                    indicatorBinding.imgView.setImageResource(R.drawable.permission_indicator_normal)
                }
            }
            binding.permissionIndicator.addView(indicatorBinding.root)
        }
    }


    class MyFragmentPagerAdapter(fragmentActivity: FragmentActivity, private val pageList: ArrayList<ShipweFragment>) : FragmentStateAdapter(fragmentActivity) {
        override fun createFragment(position: Int): Fragment {
            return pageList[position]
        }

        override fun getItemCount(): Int {
            return pageList.size
        }
    }

    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_PERMISSION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_PERMISSION_END)
    }
}